package com.yang.flower.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.flower.common.Result;
import com.yang.flower.entity.Role;
import com.yang.flower.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description: 角色控制器
 * @Author: Yang
 * @DateTime: 2022/12/9 15:42
 **/
@RestController
@CrossOrigin
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    //分页查询
    @GetMapping("/page")
    public Page<Role> page(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String name){
        Page<Role> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name !=null, Role::getName,name);
        queryWrapper.orderByDesc(Role::getId);
        Page<Role> pageInfo = roleService.page(page, queryWrapper);
        return pageInfo;
    }

    //新增角色信息
    @PostMapping("/add")
    public Result add(@RequestBody Role role){
        return Result.success(roleService.save(role));
    }

    //修改角色信息
    @PutMapping("/edit")
    public Result edit(@RequestBody Role role){
        return Result.success(roleService.saveOrUpdate(role));
    }

    //根据id删除角色
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        return Result.success(roleService.removeById(id));
    }

    //批量删除角色
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<String> ids){
        return Result.success(roleService.removeByIds(ids));
    }

    //绑定角色和菜单的关系
    @PostMapping("/roleMenu/{roleId}")
    public Result roleMenu(@PathVariable Integer roleId,@RequestBody List<Integer> menuIds){
        roleService.setRoleMenu(roleId,menuIds);
        return Result.success();
    }

    @GetMapping("/roleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId){
        return Result.success(roleService.getRoleMenu(roleId));
    }

    @GetMapping
    public Result findAll(){
        return Result.success(roleService.list());
    }

}
